package net.huashitong.Project.web;

import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.utils.NumberUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Project.entity.NewProjects;
import net.huashitong.Project.filter.NewProjectsFilter;
import net.huashitong.Project.responseModel.*;
import net.huashitong.Project.service.NewProjectsService;
import net.huashitong.Project.service.NodeNewschedulesProcess;
import net.huashitong.Project.util.EffecComparator;
import net.huashitong.node.entity.NodeNewschedules;
import net.huashitong.node.service.NodeNewschedulesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.DecimalFormat;
import java.util.*;

@Controller
@RequestMapping(value = "/chart/")
public class ItemOverViewController extends JsonBaseController {

    @Override
    protected String getView(String s) {
        return null;
    }

    @Autowired
    private NewProjectsService newProjectsService;
    @Autowired
    private NodeNewschedulesService nss;
    @Autowired
    private NodeNewschedulesProcess nodeNewschedulesProcess;

    @ResponseBody
    @RequestMapping(value = "queryByType", method = RequestMethod.GET)
    public Message queryByType(String industryType) {
        NewProjectsFilter filter = new NewProjectsFilter();
        filter.setIndustryType(industryType);
        //获取所有项目
        List<NewProjects> list = newProjectsService.getProjectInfo3(filter);
        List<ItemResponseModel> modelList = new ArrayList<>();

        //获取小节点，已确定
        List<NodeNewschedules> allNode = nss.getNodeInfo(null, "2", null, "1");

        Map<String, List<NodeNewschedules>> nodeMap = new HashMap<>();           //所有节点
        Map<String, List<NodeNewschedules>> nodeFinishedMap = new HashMap<>();   //完成节点
        Map<String, List<NodeNewschedules>> nodeBeginedMap = new HashMap<>();    //已开始
        Map<String, List<NodeNewschedules>> nodeNoMap = new HashMap<>();         //未开始


        for (NewProjects project : list) {
            List<NodeNewschedules> newNewschedules = new ArrayList<>();         //所有节点
            List<NodeNewschedules> newNewschedulesFinisted = new ArrayList<>(); //完成节点
            List<NodeNewschedules> newNewschedulesBegined = new ArrayList<>();  //已开始
            List<NodeNewschedules> newNewschedulesNo = new ArrayList<>();       //未开始
            for (NodeNewschedules node : allNode) {
                if (project.getSysId().equals(node.getProjectId())) {
                    newNewschedules.add(node);
                    if ("2".equals(node.getStatus())) {  //已完成
                        newNewschedulesFinisted.add(node);
                    }
                    if ("1".equals(node.getStatus())) {  //已开始
                        newNewschedulesBegined.add(node);
                    }
                    if ("0".equals(node.getStatus())) {  //未开始
                        newNewschedulesNo.add(node);
                    }
                }
            }
            nodeMap.put(project.getSysId(), newNewschedules);
            nodeFinishedMap.put(project.getSysId(), newNewschedulesFinisted);
            nodeBeginedMap.put(project.getSysId(), newNewschedulesBegined);
            nodeNoMap.put(project.getSysId(), newNewschedulesNo);
        }
        for (NewProjects newProject : list) {
            String projectId = newProject.getSysId();
            //遍历查询每个项目下的所有节点
            //需要的所有小节点
            List<NodeNewschedules> allNeed = nodeMap.get(newProject.getSysId());
            //完成的小节点:status=2
            List<NodeNewschedules> allFinishNeed = nodeFinishedMap.get(newProject.getSysId());
            //已开始小节点数
            List<NodeNewschedules> allBeginNeed = nodeBeginedMap.get(newProject.getSysId());
            //未开始小节点数
            List<NodeNewschedules> allNoBeginNeed = nodeNoMap.get(newProject.getSysId());
//            List<NodeNewschedules> allNullNeed = nss.getNode2FinishByProjectId(projectId,null);

            int noBeginNeed = allNeed.size() - allFinishNeed.size() - allBeginNeed.size();

            if (allBeginNeed == null || allBeginNeed.size() == 0) {
                modelList.add(new ItemResponseModel(
                                newProject,
                                allNeed.size(),
                                allFinishNeed.size(),
                                allBeginNeed.size(),
                                noBeginNeed,
                                null
                        )
                );
            } else {
                modelList.add(new ItemResponseModel(
                                newProject,
                                allNeed.size(),
                                allFinishNeed.size(),
                                allBeginNeed.size(),
                                noBeginNeed,
                                allBeginNeed.get(0)
                        )
                );
            }
        }

        Collections.sort(modelList, new Comparator<ItemResponseModel>() {
            public int compare(ItemResponseModel p1, ItemResponseModel p2) {
                if (p2.getNodeFinish() == 0 || p2.getNodeNeed() == 0 || p1.getNodeFinish() == 0 || p1.getNodeNeed() == 0) {
                    return 0;
                }
                double i = (p2.getNodeFinish() / p2.getNodeNeed() * 100) * 1.0 - (p1.getNodeFinish() / p1.getNodeNeed() * 100) * 1.0;
                if (i == 0) {
                    return -1;
                } else if (i > 0) {
                    return 1;
                } else {
                    return 0;
                }
            }
        });
        return coverMessage("200", "获取成功", modelList);
    }

    /**
     * 查询某个项目简单时间信息
     *
     * @param projectId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getDetailTimeByProjectId", method = RequestMethod.GET)
    public Message getDetailByProjectId(String projectId) {
        NewProjectsFilter filter = new NewProjectsFilter();
        filter.setSysId(projectId);
        //获取指定项目
        List<NewProjects> list = newProjectsService.getProjectInfo(filter);
        NewProjects newProject = list.get(0);

        //拼接返回的projectDetailModel
        ProjectDetailModel projectDetailModel = new ProjectDetailModel();
        projectDetailModel.setProjectName(newProject.getName());                    //项目名称
        projectDetailModel.setResUnit(newProject.getResDept());                     //责任单位
        projectDetailModel.setItemGrade(newProject.getProjectClassification());     //项目等级
        String beginTime = newProject.getPlanBeginDate();
        if (StringUtils.isNotBlank(beginTime)) {
            projectDetailModel.setBeginTime(beginTime);                 //开始时间
        } else {
            projectDetailModel.setTimeState("项目暂未开始");
            projectDetailModel.setBeginTime("----");
        }
        String endTime = newProject.getFactFinishDate();
        if (StringUtils.isNotBlank(endTime)) {
            projectDetailModel.setEndTime(endTime);                     //结束时间
        } else {
            projectDetailModel.setTimeState("项目暂未完成");
            projectDetailModel.setEndTime("----");
        }
        ProcessResultModel proModel = nodeNewschedulesProcess.getjj(projectId, null);
        projectDetailModel.setPlanTime(proModel.getPlanTimes());        //计划用时
        projectDetailModel.setFactTime(proModel.getCountFinishDays());  //实际用时
        if (StringUtils.isNotBlank(beginTime) && StringUtils.isNotBlank(endTime)) {
            projectDetailModel.setTimeState("完成");
        }
        //开始时间
        return coverMessage("200", "项目简单时间信息", projectDetailModel);
    }

    /**
     * 各部门的节点完成情况
     *
     * @param projectId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getProDetailOrderByDept", method = RequestMethod.GET)
    public Message getProDetailDept(String projectId) {
        Map<String, ProcessResultModel> deptNodeMap = new HashMap<String, ProcessResultModel>();
        List<NodeNewschedules> deptList = nss.getAllDeptByProId();
        int flag = 0;

        for (NodeNewschedules dept : deptList) {
            ProcessResultModel processResultModel = nodeNewschedulesProcess.getjj(projectId, dept.getResDept());
            if (processResultModel != null) {
                deptNodeMap.put("" + flag++, processResultModel);
            }
//            deptNodeMap.put(""+flag++,processResultModel);
        }
        return coverMessage("200", "获取各部门考核情况成功", deptNodeMap);
    }

    @ResponseBody
    @RequestMapping(value = "getdeptdetail", method = RequestMethod.GET)
    public Message getdeptdetail(String projectId, String dept) {
        ProcessResultModel processResultModel = nodeNewschedulesProcess.getjj(projectId, dept);
        return coverMessage("200", "获取项目时间详情成功", processResultModel);
    }

    //总完成任务情况
    @ResponseBody
    @RequestMapping(value = "gettaskfinisheddetail", method = RequestMethod.GET)
    public Message getTaskFinishedDetail(String projectId) {
        NewProjectsFilter filter = new NewProjectsFilter();
        List<EachNodeDetailModel> eachNodeDetailModels = new ArrayList<EachNodeDetailModel>();
        TaskNodeDetailModel taskNodeDetailModel = new TaskNodeDetailModel();

        ProcessResultModel processResultModel = nodeNewschedulesProcess.getjj(projectId, null);
        taskNodeDetailModel.setCountFinishDays(processResultModel.getCountFinishDays());
        taskNodeDetailModel.setEarlyFinishedDays(processResultModel.getBeyondFinishedDays());

        filter.setSysId(projectId);
        //获取所有项目
        List<NewProjects> list = newProjectsService.getProjectInfo(filter);
        //获取指定项目
        NewProjects newProjects = list.get(0);
        //需要的所有小节点
        List<NodeNewschedules> allNode = nss.queryListByProjectId(projectId, "2", null, "1", null);
        //需要的所有大节点
        List<NodeNewschedules> bigNode = nss.getNeedBigNodeByProjectId(projectId);
        Map<String, String> bigNodeMap = new HashMap<String, String>();
        for (NodeNewschedules node : bigNode) {
            bigNodeMap.put(node.getNodeId(), node.getNodeName());
        }

        List<String> nodeList = new ArrayList<String>();
        for (NodeNewschedules node : allNode) {
            if (!nodeList.contains(node.getNodeIds()) && !"0".equals(node.getNodeIds())) {
                nodeList.add(node.getNodeIds());
            }
        }
        Map<String, EachNodeDetailModel> nodesMap = new HashMap<String, EachNodeDetailModel>();
        //所有节点
        for (String node : nodeList) {
            int factTime = 0;   //实际时间
            int planTime = 0;   //计划时间
            for (NodeNewschedules n : allNode) {
                if ("2".equals(n.getStatus()) && node.equals(n.getNodeIds()) && StringUtils.isNotBlank(n.getFactTime())) {
                    factTime = factTime + Integer.parseInt(n.getFactTime());
                }
                if ("2".equals(n.getStatus()) && node.equals(n.getNodeIds()) && StringUtils.isNotBlank(n.getPlanTime())) {
                    planTime = planTime + Integer.parseInt(n.getPlanTime());
                }
            }

            EachNodeDetailModel eachNodeDetailModel = new EachNodeDetailModel();
            eachNodeDetailModel.setFactTime(factTime);
            eachNodeDetailModel.setPlanTime(planTime);
            eachNodeDetailModel.setTimeState(planTime - factTime);    //正数表示超前；0表示正常；负数表示逾期
            eachNodeDetailModel.setNodeId(node);
            eachNodeDetailModel.setProjectId(projectId);
            eachNodeDetailModel.setNode1Name(bigNodeMap.get(node));
            nodesMap.put(node, eachNodeDetailModel);
            eachNodeDetailModels.add(eachNodeDetailModel);
        }
        List<NodeEffecModel> nodeEffecList = new ArrayList<NodeEffecModel>();
        for (EachNodeDetailModel model : eachNodeDetailModels) {
            int ft = model.getFactTime();
            int pt = model.getPlanTime();
            DecimalFormat df = new DecimalFormat("##0.00");
            if (pt == 0) {
                continue;
            }
            double res = NumberUtils.doubleFormat((double) (pt - ft) / pt, 4);
            NodeEffecModel nodeEffec = new NodeEffecModel(model.getTimeState(), model.getNodeId(), res);
            model.setPercent(res);
            nodeEffecList.add(nodeEffec);
        }
//        Collections.sort(eachNodeDetailModels, new Comparator<EachNodeDetailModel>(){
//            public int compare(EachNodeDetailModel p1, EachNodeDetailModel p2) {
//                double data1 = p1.getPercent();
//                double data2 = p2.getPercent();
//                if(data1 == data2){
//                    return 0;
//                }else if(data1 > data2){
//                    return -1;
//                }else{
//                    return 1;
//                }
//            }
//        });
//        taskNodeDetailModel.setNodes(eachNodeDetailModels);
        taskNodeDetailModel.setNodes(nodesMap);
        Collections.sort(nodeEffecList, new EffecComparator());
//        myprint(nodeEffecList);
        List<NodeEffecModel> hightEffect = new ArrayList<NodeEffecModel>();
        List<NodeEffecModel> lowEffect = new ArrayList<NodeEffecModel>();
        Map<String, List<NodeEffecModel>> effecListMap = new HashMap<String, List<NodeEffecModel>>();
        if (nodeEffecList.size() >= 3) {
            for (int i = 0; i < 3; i++) {
                hightEffect.add(nodeEffecList.get(i));
            }
            for (int i = nodeEffecList.size() - 1; i > nodeEffecList.size() - 4; i--) {
                lowEffect.add(nodeEffecList.get(i));
            }

        } else {
            for (int i = 0; i < nodeEffecList.size(); i++) {
                hightEffect.add(nodeEffecList.get(i));
            }

            for (int i = nodeEffecList.size() - 1; i > -1; i--) {
                lowEffect.add(nodeEffecList.get(i));
            }
        }

        effecListMap.put("hightEffect", hightEffect);//效率最高
        effecListMap.put("lowEffect", lowEffect);    //效率最低

        taskNodeDetailModel.setEffecListMap(effecListMap);
        return coverMessage("200", "获取总完成任务情况成功", taskNodeDetailModel);
    }

    public static void myprint(List<NodeEffecModel> list) {
        Iterator it = list.iterator(); // 得到迭代器，用于遍历list中的所有元素
        while (it.hasNext()) {// 如果迭代器中有元素，则返回true
            System.out.println("\t" + it.next());// 显示该元素
        }
    }
}
